package at.fhv.components.source;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

import at.fhv.framework.CommonImageProcessingHelper;
import at.fhv.framework.events.ImageEvent;
import at.fhv.framework.listeners.ImageProcessingListener;
import at.fhv.framework.listeners.RefireListener;

/**
 * The ImageSource class.
 * 
 * @author Michael Sieber
 */
public class ImageSource implements ImageProcessingListener, RefireListener {
	private String _imagePath;
	private PlanarImage _image;
	private CommonImageProcessingHelper _helper;

	/**
	 * 
	 */
	public ImageSource() {
		_imagePath = "C:/tmp/loetstellen.jpg";
		_helper = new CommonImageProcessingHelper(this);
		loadImage();
	}

	/**
	 * Load the image
	 */
	private void loadImage() {
		try {
			_image = JAI.create("fileload", _imagePath);

			if (_image == null) {
				System.out.println("Image is null.");
			}
		} catch (Exception e) {
			System.out.println("Unable to load image from: " + _imagePath);
		}

		imageChanged(new ImageEvent(this, _image));
	}

	/**
	 * Get the image path
	 * 
	 * @return The image path
	 */
	public String getPath() {
		return _imagePath;
	}

	/**
	 * Set the image path
	 * 
	 * @param path The image path to set
	 */
	public void setPath(String path) {
		_imagePath = path;
		loadImage();
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void refire() {
		loadImage();
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void imageChanged(ImageEvent event) {
		_helper.fireImageProcessingEvent(event);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void addRefireListener(RefireListener listener) {
		_helper.addRefireListener(listener);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void removeRefireListener(RefireListener listener) {
		_helper.removeRefireListener(listener);
	}

	/**
	 * Add an image change listener
	 * 
	 * @param listener The image change listener to add
	 */
	public void addImageChangeListener(ImageProcessingListener listener) {
		_helper.addImageProcessingListener(listener);

		// force all previous beans to refire their event
		_helper.fireRefireEvent();

		// load the image and fire the change event
		loadImage();
	}

	/**
	 * Remove an image change listener
	 * 
	 * @param listener The image change listener to remove
	 */
	public void removeImageChangeListener(ImageProcessingListener listener) {
		_helper.removeImageProcessingListener(listener);
	}
}
